<?php

/**
 * Created by PhpStorm.
 * User: shwy
 * Date: 2017/5/18
 * Time: 15:55
 * 商品管理
 */
class goods extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->load->model('goods_model');
        $this->load->model('goodsImage_model');
        $this->load->model('goodsStockPrice_model');
        $this->load->model('goodsSpecification_model');
        $this->load->model('goodsCategory_model');
        $this->load->model('supplier_model');
        $this->load->library('Qiniu');


    }

    /**
     * 商品列表
     */
    public function index()
    {

        $page_num = $this->config->item('fenye')['pageNum']; //每页的数据
        $start_position = ''; //初始数据
        $page = ($this->input->get('page')); //获取页码数量
        if (!$page) {
            $num = 1;
            $start_position = ($num - 1) * $page_num;
        } else {
            $start_position = ($page - 1) * $page_num;
        }

        //判断搜索内容是否存在存在就继续
        if ($this->input->get('search')) {
            $searchArg = [
                'field' => 'name',
                'arg' => $this->input->get('search'),
                'side' => 'both'
            ];

            $goods = $this->goods_model->search('*', 0, $searchArg, $page_num, $start_position);
//            print_r($data);
//            die();
//            $viewData = [
//                'list' => $data[0],  //这里得到从数据库中的当页数据
//                'totalNum' => count($data['total_num']), //这里得到从数据库中的总页数
//                'pageNum' => $page_num //每页显示多少条
//            ];
//            $this->load->view('/admin/goods/list', $viewData);
        } else {

//            print_r(123);
//            die();
//            die();
            $goods = $this->goods_model->page('goods', 0, $page_num, $start_position); //limit查询的数据


//            echo '<pre>';
//            print_r($goods);
//            die();



        }

        if ($goods[0]) {
            $ids = array_column($goods[0], 'id');  //取出ist的id
            $ckIds = array_column($goods[0], 'ckId'); //取出51ck的ckid

            //ist的商品
            foreach ($ids as $v) {
                $arg = [
                    'product_id' => $v,
                    'is_main' => 1
                ];
                $arg2 = [
                    'product_id' => $v,
                ];
                //查询ist图片
                $istImage[] = $this->goodsImage_model->getByFieldQueryData('product_id,file_path', $arg, 0);
                //查询ist的是否有规格信息
                $istSpecification[] = $this->goodsStockPrice_model->getByFieldQueryData('product_id,stock,specification_group_names', $arg2, 0);
                //插叙ist库存
                $istStock[] = $this->goodsStockPrice_model->getByFieldQueryData('product_id,stock,specification_group_names', $arg2, 1);
            }

            //51ck的商品
            foreach ($ckIds as $k2 => $v2) {
                $arg3 = [
                    'product_id' => $v2,
                    'is_main' => 1
                ];
                $arg4 = [
                    'product_id' => $v2
                ];
                $ckImage[] = $this->goodsImage_model->getByFieldQueryData('product_id,file_path', $arg3, 0); //limit查询的数据
                //查询51ck的是否有规格信息
                $ckSpecification[] = $this->goodsStockPrice_model->getByFieldQueryData('product_id,stock,specification_group_names', $arg4, 0); //limit查询的数据
                //查询51ck的是否有库存
                $ckStock[] = $this->goodsStockPrice_model->getByFieldQueryData('product_id,stock,specification_group_names', $arg4, 1); //limit查询的数据
            }

//                echo '<pre>';
//                die();
            //循环ist商品的规格和图片,并加入
            foreach ($goods[0] as $k3 => $v3) {
                foreach ($istImage as $k4 => $v4) {
                    //存在并且不为空
                    if (isset($v4['file_path']) && !empty($v4['file_path'])) {
                        //todo 不相等的时候为什么能加进去?
                        if ($v4['product_id'] != $v3['id']) {
                            $goods[0][$k4]['file_path'] = $v4['file_path'];
                        } else {
                            $goods[0][$k4]['file_path'] = 123456;
                        }
                    } else {
                        $goods[0][$k4]['file_path'] = 789;

                    }
                }
            }
            unset($v3);
            foreach ($istSpecification as $k6 => $v6) {
                foreach ($goods[0] as $k5 => $v5) {
                    if (isset($v6['specification_group_names']) && $v6['specification_group_names'] != '暂无规格' ) {
                        if ($v6['product_id'] != $v5['ckId']) {
                            $goods[0][$k6]['isSpecification'] = 1;
                            break;
                        }
                    }
                }
            }
            unset($v5);

            //查询爱思特的所有库存集合
            foreach ($istStock as $k10 => $v10) {
                $istReStock[] = array_sum(array_column($v10, 'stock'));
            }
            unset($v10);
            //并加入其数据中
            foreach ($goods[0] as $k11 => $v11) {
                foreach ($istReStock as $k12 => $v12) {
                    $goods[0][$k12]['stock'] = $v12;
                }
            }
            unset($v11);

//                echo '<pre>';
//                print_r($goods);
//                die();

            //循环51ck商品的规格和图片
            foreach ($goods[0] as $k7 => $v7) {
                foreach ($ckImage as $k8 => $v8) {
                    //存在并且不为空
                    if ($v7['ckId']) {
                        if (isset($v8['file_path']) && !empty($v8['file_path'])) {
                            //todo 不相等的时候为什么能加进去?
//                                __logInfo('produ',$v8['product_id']);
//                                __logInfo('ckId',$v7['ckId']);
                            if ($v8['product_id'] == $v7['ckId']) {
//                                    __logInfo('ckId',$v8['file_path']);

                                $goods[0][$k8]['file_path'] = $v8['file_path'];
                            } else {
                                $goods[0][$k8]['file_path'] = $v8['file_path'];
                            }
                        }
                    }

                }
            }
//                unset($v7);
//                echo '<pre>';
//                print_r($ckSpecification);
//                die;
            //ckSpecification 放入第一层循环，如果又一次为真就break;
            foreach ($ckSpecification as $k10 => $v6) {
                foreach ($goods[0] as $k9 => $v9) {
                    if ($v9['ckId']) {
                        if (isset($v6['specification_group_names']) && $v6['specification_group_names'] != '暂无规格') {
                            if ($v6['product_id'] == $v9['ckId']) {
                                $goods[0][$k10]['isSpecification'] = 1;
                                break;
                            }
                        }
                    }

                }
            }
//            echo '<pre>';
//            print_r($goods);
//            die;
            unset($v9);


            //循环51ck的库存
            foreach ($ckStock as $k13 => $v13) {
                $ckReStock[] = array_sum(array_column($v13, 'stock'));

            }
            unset($v13);
            foreach ($goods[0] as $k14 => $v14) {
                foreach ($ckReStock as $k15 => $v15) {
                    if ($v14['ckId'] && $v15) {
                        $goods[0][$k15]['stock'] = $v15;
                    }
                }
            }

//                echo '<pre>';
//                print_r($goods);
//                die();


            $viewData = [
                'list' => $goods[0],  //这里得到从数据库中的当页数据
                'totalNum' => $goods['total_num'], //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];

        } else {
            $viewData = [
                'list' => '',  //这里得到从数据库中的当页数据
                'totalNum' => $goods['total_num'], //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];
        }

        $this->load->view('/admin/goods/list', $viewData);
    }

//添加功能
    public function add()
    {
        // 上传文件，这里的pic是视图中file控件的name属性
        //图片1-4上传
        if ($_FILES['image1']['error'] == 0) {
            $mime1 = substr($_FILES['image1']['name'], strrpos($_FILES['image1']['name'], '.')); //取得上传图片的后缀名
            $image1Name = 'goods/' . date('YmdHis') . rand(1000, 2000) . $mime1;
            $this->qiniu->upload($_FILES['image1']['tmp_name'], $image1Name);
            $image1 = $this->config->item('qiniu')['url'].$image1Name;
        } else {
            $image1 = '';
        }

        if ($_FILES['image2']['error'] == 0) {
            $mime2 = substr($_FILES['image2']['name'], strrpos($_FILES['image2']['name'], '.')); //取得上传图片的后缀名
            $image2Name = 'goods/' . date('YmdHis') . rand(1000, 2000) . $mime2;
            $this->qiniu->upload($_FILES['image2']['tmp_name'], $image2Name);
            $image2 = $this->config->item('qiniu')['url'].$image2Name;
        } else {
            $image2 = '';
        }

        if ($_FILES['image3']['error'] == 0) {
            $mime1 = substr($_FILES['image3']['name'], strrpos($_FILES['image3']['name'], '.')); //取得上传图片的后缀名
            $image3Name = 'goods/' . date('YmdHis') . rand(1000, 2000) . $mime1;
            $this->qiniu->upload($_FILES['image3']['tmp_name'], $image3Name);
            $image3 = $this->config->item('qiniu')['url'].$image3Name;
        } else {
            $image3 = '';
        }

        if ($_FILES['image4']['error'] == 0) {
            $mime1 = substr($_FILES['image4']['name'], strrpos($_FILES['image4']['name'], '.')); //取得上传图片的后缀名
            $image4Name = 'goods/' . date('YmdHis') . rand(1000, 2000) . $mime1;
            $this->qiniu->upload($_FILES['image4']['tmp_name'], $image4Name);
            $image4 = $this->config->item('qiniu')['url'].$image4Name;
        } else {
            $image4 = '';
        }

//        print_r($image1);
//        die;

        if(!isset($_POST['price'])){
            $_POST['price'] = 0;
        }

        //商品的基础信息添加
        $baseInfo = [
            'product_no' => $_POST['productNo'], //商品编码
            'name' => $_POST['name'],       //商品名称
            'goodsUnit' => $_POST['goodsUnit'], //商品单位
            'jbarcode' => $_POST['jbarcode'], //商品条形码
            'canshu' => $_POST['canshu'], //商品参数
            'detail' => $_POST['detail'], //商品详情
            'source' => 'ist', //商品来源
            'create_time' => time(), //商品来源
            'update_time' => time(), //商品来源
            'is_can_size' => $_POST['isCanSize'],

            'one_category' => $_POST['oneCategory'],
            'two_category' => $_POST['twoCategory'],
            'three_category' => $_POST['threeCategory'],

            'specificationJson' => $_POST['specificationJson'],
            'price' => $_POST['price'], //商品价格

            'supplier' =>$_POST['supplier']
        ];

//        //返回商品添加后的id
        $insetId = $this->goods_model->addId($baseInfo);

//        print_r($insetId);
//        die();

        //添加商品规格名和规格值
        //循环得到的数据,name的则为第一级别,value里面的则为第二级别
        //在第一级别循环完毕之后,通过返回的主键id,加到第二级别中,作为parent_specification上级规格id
//        $a = "[{"name":"啊:","value":["额鹅鹅鹅","呃呃呃"]},{"name":"王企鹅:","value":["钱钱钱","去去去","去问问"]}]";
        $specificationJson = json_decode($_POST['specificationJson'], true);

//        $myfile = fopen("a.txt", "w");
//        fwrite($myfile, json_encode($specificationJson));
//        die();
        foreach ($specificationJson as $k4 => $v4) {
            $goodsStockPrice = [
                'name' => substr($v4['name'], 0, -1), //规格名
                'product_id' => $insetId, //商品id
                'parent_specification' => '', //上级规格（为空即第一级规格）
                'create_time' => time(),
                'update_time' => time(),
            ];

//            $myfile = fopen("a.txt", "w");
//        fwrite($myfile, json_encode($goodsStockPrice));

            $goodsStockPriceId = $this->goodsSpecification_model->addId($goodsStockPrice);

//            $myfile = fopen("a.txt", "w");
//            fwrite($myfile, json_encode($goodsStockPriceId));

            if ($goodsStockPriceId) {
                foreach ($v4['value'] as $k5 => $v5) {
                    $goodsStockPrice2 = [
                        'name' => $v5, //规格名
                        'product_id' => $insetId, //商品id
                        'parent_specification' => $goodsStockPriceId, //上级规格（为空即第一级规格）
                        'create_time' => time(),
                        'update_time' => time(),
                    ];

                    $this->goodsSpecification_model->addId($goodsStockPrice2);
                }
            }
        }


        //添加商品规格和价格表
        $priceAndStockJson = json_decode($_POST['priceAndStockJson'], true);

        if ($_POST['isCanSize']) {
            foreach ($priceAndStockJson as $k3 => $v3) {
                $data = [
                    'product_stock_priceId' => '',  //51的商品库id
                    'group_no' => $v3['groupNo'], //规格自编号
                    'product_id' => $insetId, //商品id
                    'specification_group_names' => $v3['groupValue'][0], //规格组合值
                    'stock' => '', //库存数量
                    'price' => $v3['groupPrice'], //商品价格
                    'create_time' => time(),
                    'update_time' => time(),
                ];

                $this->goodsStockPrice_model->add($data);
            }

        } else {
            //没有启用规格的插入
            $priceAndStockJson = [
                'product_stock_priceId' => '',  //51的商品库id
                'group_no' => '', //规格自编号
                'product_id' => $insetId, //商品id
                'stock' => 0, //库存
                'price' => $_POST['price'], //商品价格
                'create_time' => time(),
                'update_time' => time(),
            ];
            $this->goodsStockPrice_model->addId($priceAndStockJson);
        }

//        print_r($insetId);
//        die;

        //添加商品图片表
        $imageInfo = [
            0 => [
                'product_id' => $insetId,
                'file_path' => $image1,
                'is_main' => 1,
                'create_time' => time(),
                'update_time' => time(),
            ],
            1 => [
                'product_id' => $insetId,
                'file_path' => $image2,
                'is_main' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ],
            2 => [
                'product_id' => $insetId,
                'file_path' => $image3,
                'is_main' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ],
            3 => [
                'product_id' => $insetId,
                'file_path' => $image4,
                'is_main' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ],
        ];
//
        foreach ($imageInfo as $k2 => $v2) {
            $this->goodsImage_model->add($v2);
        }

        $return = [
            'success' => 1
        ];
        echo json_encode($return);
//        $myfile = fopen("a.txt", "w");
//        fwrite($myfile, json_encode($return));
//        return json_encode($return);
//        redirect('/admin/goods/index?page=1');

    }

//添加页面
    public function addView()
    {

        //添加供应商列表
        $data['supplier'] = $this->supplier_model->getData('id,name', 1);

        $this->load->view('/admin/goods/add',$data);
    }

//编辑功能
    public function edit()
    {




        //不等于0都说明上传失败了,没上传
        if ($_FILES['image1']['error'] == 0) {
            $mime1 = substr($_FILES['image1']['name'], strrpos($_FILES['image1']['name'], '.')); //取得上传图片的后缀名
            $image1Name = 'goods/' . date('YmdHis') . rand(1000, 2000) . $mime1;
            $this->qiniu->upload($_FILES['image1']['tmp_name'], $image1Name);
            $image['0'] = $this->config->item('qiniu')['url'].$image1Name;
        } else {
            $image['0'] = '';
        }

        if ($_FILES['image2']['error'] == 0) {
            $mime2 = substr($_FILES['image2']['name'], strrpos($_FILES['image2']['name'], '.')); //取得上传图片的后缀名
            $image2Name = 'goods/' . date('YmdHis') . rand(1000, 2000) . $mime2;
            $this->qiniu->upload($_FILES['image2']['tmp_name'], $image2Name);
            $image['1'] = $this->config->item('qiniu')['url'].$image2Name;
        } else {
            $image['1'] = '';
        }

        if ($_FILES['image3']['error'] == 0) {
            $mime1 = substr($_FILES['image3']['name'], strrpos($_FILES['image3']['name'], '.')); //取得上传图片的后缀名
            $image3Name = 'goods/' . date('YmdHis') . rand(1000, 2000) . $mime1;
            $this->qiniu->upload($_FILES['image3']['tmp_name'], $image3Name);
            $image['2'] = $this->config->item('qiniu')['url'].$image3Name;
        } else {
            $image['2'] = '';
        }

        if ($_FILES['image4']['error'] == 0) {
            $mime1 = substr($_FILES['image4']['name'], strrpos($_FILES['image4']['name'], '.')); //取得上传图片的后缀名
            $image4Name = 'goods/' . date('YmdHis') . rand(1000, 2000) . $mime1;
            $this->qiniu->upload($_FILES['image4']['tmp_name'], $image4Name);
            $image['3'] = $this->config->item('qiniu')['url'].$image4Name;
        } else {
            $image['3'] = '';
        }


//        print_r($image);
//        die();

//        $maxIdWhere = [
//            'product_id' => $_POST['id']
//        ];
//        $imageId = $this->goodsImage_model->getMaxId('id', $maxIdWhere); //返回数组
//        $imageWhere = [
//            'id' => $imageId['id']
//        ];
//        print_r($imageWhere);
//        die();

        //商品图片id
        $arg = [
            'product_id' => $_POST['id']
        ];

        $this->goodsSpecification_model->remove($arg);
        $this->goodsStockPrice_model->remove($arg);

        //查询关于这个id所有的图片
        $imageId = $this->goodsImage_model->getByFieldQueryData('id,file_path', $arg, 1); //返回数组


        $specificationJson = json_decode($_POST['specificationJson'], true);

//        $myfile = fopen("a.txt", "w");
//        fwrite($myfile, json_encode($specificationJson));
//        die();
        foreach ($specificationJson as $k4 => $v4) {
            $goodsStockPrice = [
                'name' => substr($v4['name'], 0, -1), //规格名
                'product_id' => $_POST['id'], //商品id
                'parent_specification' => '', //上级规格（为空即第一级规格）
                'create_time' => time(),
                'update_time' => time(),
            ];

//            $myfile = fopen("a.txt", "w");
//        fwrite($myfile, json_encode($goodsStockPrice));

            $goodsStockPriceId = $this->goodsSpecification_model->addId($goodsStockPrice);

//            $myfile = fopen("a.txt", "w");
//            fwrite($myfile, json_encode($goodsStockPriceId));

            if ($goodsStockPriceId) {
                foreach ($v4['value'] as $k5 => $v5) {
                    $goodsStockPrice2 = [
                        'name' => $v5, //规格名
                        'product_id' => $_POST['id'], //商品id
                        'parent_specification' => $goodsStockPriceId, //上级规格（为空即第一级规格）
                        'create_time' => time(),
                        'update_time' => time(),
                    ];

                    $this->goodsSpecification_model->addId($goodsStockPrice2);
                }
            }
        }


        //添加商品规格和价格表
        $priceAndStockJson = json_decode($_POST['priceAndStockJson'], true);

        if ($_POST['isCanSize']) {
            foreach ($priceAndStockJson as $k3 => $v3) {
                $data = [
                    'product_stock_priceId' => '',  //51的商品库id
                    'group_no' => $v3['groupNo'], //规格自编号
                    'product_id' => $_POST['id'], //商品id
                    'specification_group_names' => $v3['groupValue'][0], //规格组合值
                    'stock' => '', //库存数量
                    'price' => $v3['groupPrice'], //商品价格
                    'create_time' => time(),
                    'update_time' => time(),
                ];

                $this->goodsStockPrice_model->add($data);
            }


        } else {
            //没有启用规格的插入
            $priceAndStockJson = [
                'product_stock_priceId' => '',  //51的商品库id
                'group_no' => '', //规格自编号
                'product_id' => $_POST['id'], //商品id
                'stock' => 0, //库存
                'price' => $_POST['price'], //商品价格
                'create_time' => time(),
                'update_time' => time(),
            ];
            $this->goodsStockPrice_model->addId($priceAndStockJson);


        }


//        print_r($image);
//        die();


//        print_r(json_encode($imageId));
//        die();
        foreach ($image as $k => $v) {
//            print_r($image[2]);
//            die();

//            foreach ($imageId)
            if ($v) {

                $imageData = [
                    'file_path' => $v
                ];

                $imageWhere = [
                    'id' => $imageId[$k]['id']
                ];

                $this->goodsImage_model->edit($imageData, $imageWhere); //返回数组
            }
        }

//        print_r($imageData);
//        die();

        if(!isset($_POST['price'])){
            $_POST['price'] = 0;
        }

        //商品的基础信息添加
        $baseInfo = [
            'name' => $_POST['name'],       //商品名称
            'goodsUnit' => $_POST['goodsUnit'], //商品单位
            'jbarcode' => $_POST['jbarcode'], //商品条形码
            'canshu' => $_POST['canshu'], //商品参数
            'detail' => $_POST['detail'], //商品详情
//            'source' => 'ist', //商品来源
            'one_category' => $_POST['oneCategory'],
            'two_category' => $_POST['twoCategory'],
            'three_category' => $_POST['threeCategory'],

            'update_time' => time(), //商品来源
            'specificationJson' => $_POST['specificationJson'],

            'price' => $_POST['price'], //商品价格

            'is_can_size' => $_POST['isCanSize'], //是否启用规格修改

//            'supplier' =>$_POST['supplier']

        ];

        //用户id
        $where = [
            'id' => $_POST['id']
        ];

        __logInfo('d',$_POST['isCanSize']);




        //是否会有添加失败的情况?
        $this->goods_model->edit($baseInfo, $where);

        $return = [
            'success' => 1
        ];
        echo json_encode($return);

    }

//编辑页面
    public function editView()
    {

        //读取用户名根据get id
        $arg = [
            'id' => $this->input->get('id')
        ];

        $data['list'] = $this->goods_model->getByFieldQueryData('*', $arg, 0);



        //如果不存在直接跳转到404页面
        if (!$data['list']) {
            redirect('/home/error');
        }


        //根据第一个id查询数据
        $arg = [
            'level' => 2,
            'one_category' => $data['list']['one_category']
        ];
        //查询二级名字
        $twoData = $this->goodsCategory_model->getByFieldQueryData('id,name', $arg, 1);

//        echo '<pre>';
//        print_r($twoData);
//        die();

        $arg = [
            'level' => 3,
            'parent_id' => $data['list']['two_category']
        ];
        //查询询三级名字
        $threeData = $this->goodsCategory_model->getByFieldQueryData('id,name', $arg, 1);

        $data['list']['two_category_name'] = $twoData;
        $data['list']['three_category_name'] = $threeData;

//
        $arg4 = [
            'product_id' => $this->input->get('id')
        ];
        $data['list']['image'] = $this->goodsImage_model->getByFieldQueryData('id,product_id,file_path', $arg4, 1);


        //规格值格式化
        $data['list']['specificationJson'] = json_decode($data['list']['specificationJson'],true);


        //查询规格名和价格
        $data['stockPriceData'] = $this->goodsStockPrice_model->getByFieldQueryData('id,group_no,specification_group_names,price', $arg4, 1);



//        $specificationData = $this->goodsSpecification_model->getByFieldQueryData('id,name,parent_specification', $arg4, 1);
////        $data['list']['price'] = $price['price'];
//
//        foreach ($specificationData as $k=>$v){
//            if(empty($v['parent_specification'])){
//                $arr[] = [
//                    'id' => $v['id'],
//                    'name' => $v['name'],
//                ];
//            }
//        }


        //查询商品的规格值和名



//        __format($data);

        $this->load->view('/admin/goods/edit', $data);
    }

//删除功能
    public function remove()
    {

        $postData = $this->input->post();

        if ($postData) {
            if (!$postData) {
                redirect('/admin/goods/index');
            }

            $post = $this->input->post('del_id');
//            print_r($post);
//            die();
            foreach ($post as $v) {
                $where = [
                    'id' => $v
                ];

                $this->goods_model->remove($where);
            }

            redirect('/admin/goods/index?page=1');
        } else {
            $where = [
                'id' => $this->input->get('id')
            ];

            //是否会有添加失败的情况?
            $this->goods_model->remove($where);
            redirect('/admin/goods/index?page=1');

        }

//        //是否会有添加失败的情况?
//        $resultData =  $this->goods_model->remove($data);
//        if($resultData){
//            echo '<script>alert("删除成功")</script>';
//            redirect('/admin/goods/index');
//        }
    }

//分类管理静态页面
    public function category()
    {
        $this->load->view('/admin/goods/category');
    }


    //商品分类一级/二级/三级接口: 辅助add,edit,remove是三个接口的回调地址
    public function categoryData()
    {
        $data = [
            0 => [
                'category' => 2,
                'name' => '物料包',
            ],
            1 => [
                'category' => 3,
                'name' => '书籍'
            ],
            2 => [
                'category' => 4,
                'name' => '打印机耗材'
            ],
            3 => [
                'category' => 8,
                'name' => '供应商商品'
            ],
            4 => [
                'category' => 9,
                'name' => '打印机租赁'
            ],
        ];

        foreach ($data as $k => $v) {
            $arg = [
                'level' => 2,
                'one_category' => $v['category']
            ];
            //查询二级名字
            $twoData = $this->goodsCategory_model->getByFieldQueryData('id,name,one_category,level', $arg, 1);

            $data[$k]['two'] = $twoData;
        }


        foreach ($data as $k2 => $v2) {
            foreach ($v2['two'] as $k3 => $v3) {
                $arg = [
                    'level' => 3,
                    'parent_id' => $v3['id']
                ];
                //查询询三级名字
                $threeData = $this->goodsCategory_model->getByFieldQueryData('id,name,one_category,level', $arg, 1);

                $data[$k2]['two'][$k3]['three'] = $threeData;

            }
        }


        echo json_encode($data, JSON_UNESCAPED_UNICODE);


//     echo json_encode($data,JSON_UNESCAPED_UNICODE);


    }


//添加二级和三级分类接口
    public function addCategory()
    {
        if (isset($_POST['oneCategory']) && isset($_POST['twoCategory'])) {

            //根据twoCategory去查询 product_categoryId，如果有就是这个，如果没有就是id
            $arg = [
                'id' => $_POST['twoCategory']
            ];
            $product_categoryId = $this->goodsCategory_model->getByFieldQueryData('product_categoryId',$arg,0);

//            print_r($product_categoryId);die;
            if($product_categoryId['product_categoryId']){
                $twoCategory = $product_categoryId['product_categoryId'];
            }else{
                $twoCategory = $_POST['twoCategory'];
            }

            $data = [
                'name' => $_POST['name'],  //分类名
                'one_category' => $_POST['oneCategory'],  //分类类型，（2物料包、3书籍、4机器耗材、8供应商商品、9打印机租）
                'level' => 3,  //分类级别，1为二级分类，2为三级分类
                'parent_id' => $twoCategory,  //父分类 为0则是二级分类
                'create_time' => time(),
                'update_time' => time()
            ];
        } else {
            $data = [
                'name' => $_POST['name'],  //分类名
                'one_category' => $_POST['oneCategory'],  //分类类型，（2物料包、3书籍、4机器耗材、8供应商商品、9打印机租）
                'level' => 2,  //分类级别，1为二级分类，2为三级分类
                'parent_id' => 0,  //父分类 为0则是二级分类
                'create_time' => time(),
                'update_time' => time()
            ];
        }

        $this->goodsCategory_model->add($data);
        echo json_encode($this->categoryData());
    }

//编辑分类名字接口
    public function editCategory()
    {
        $data = [
            'name' => $_POST['name']
        ];

        $where = [
            'id' => $_POST['id']
        ];

        $this->goodsCategory_model->edit($data, $where);
        echo json_encode($this->categoryData());
    }

//删除分类接口
    public function removeCategory()
    {

        $where = [
            'id' => $_POST['id']
        ];

        //是否会有添加失败的情况?
        $result = $this->goodsCategory_model->remove($where);
        echo json_encode($this->categoryData());
    }


    //todo 导出功能
    public function daochu()
    {

    }


}